package cn.etgps.etgps.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.etgps.etgps.R;
import cn.etgps.etgps.base.MyBasicActivity;
import cn.etgps.etgps.blmanager.TruckManager;
import cn.etgps.etgps.dataEntity.TruckDetailBean;
import cn.etgps.etgps.dataEntity.TruckDetailEntity;
import cn.etgps.etgps.dialog.DialogCreater;
import cn.etgps.etgps.event.EventBusSendFactory;
import cn.etgps.etgps.event.EventOilLogEntitiy;
import cn.etgps.etgps.utils.AppUtils;
import cn.etgps.etgps.utils.CommonUtils;
import cn.etgps.etgps.utils.Constant;
import cn.etgps.etgps.utils.GetTimeUtils;
import cn.etgps.etgps.utils.T;

/**
 * Created by xiaoyu on 2016/3/28.
 */
public class TrafficOilLogActivity extends MyBasicActivity {
    private final static String OILLOG_ENTITY = "oillog_entity";
    private final static String OILLOG_VID = "vid";
    @Bind(R.id.oil_log_variety_text)
    TextView textVariety;
    @Bind(R.id.oil_log_card_num)
    TextView editCardNum;
    //  @Bind(R.id.oil_log_date)
    TextView textDate;
    @Bind(R.id.oil_log_edit_kiml)
    EditText editKiml;
    @Bind(R.id.oil_log_edit_amount)
    EditText editAmount;
    @Bind(R.id.oil_log_edit_price)
    EditText editPrice;
    @Bind(R.id.oil_log_edit_add_price)
    TextView mPrice;
    /* @Bind(R.id.oil_log_edit_price_by_kiml)
     EditText editPriceByKiml;*/
    @Bind(R.id.oil_log_variety_layout)
    LinearLayout oilVaritey;
    @Bind(R.id.tv_year)
    TextView mYear;
    @Bind(R.id.tv_time)
    TextView mTime;
    GetTimeUtils utils;
    private OilType oilType;
    private EventOilLogEntitiy oilLogEntitiy;
    private TruckManager mUserManger = null;
    /**
     * 车辆详情请求线程
     */
    private DetailTask mDetailTask = null;
    private String vid;
    private Date time;
    private String dateStr;
    private String oilAmountStr;
    private String oilAddPriceStr;
    TextWatcher twprice = new TextWatcher() {
        String price;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            price = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {
            String sv = editAmount.getText().toString().trim();
            if (CommonUtils.isEmpty(sv)) {
                T.showShort(mContext, "请填写加油量");
                return;
            }
            if (CommonUtils.isEmpty(price)) {
                return;
            }
            float fprice = Float.valueOf(s.toString());
            float volum = Float.valueOf(sv);
            DecimalFormat df = new DecimalFormat("#.##");
            mPrice.setText(df.format(fprice * volum) + "");
            oilAddPriceStr = String.valueOf(fprice * volum);
        }
    };
    TextWatcher tw = new TextWatcher() {
        String price;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            price = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {
            String sv = editPrice.getText().toString().trim();
            if (CommonUtils.isEmpty(sv)) {
                return;
            }
            if (CommonUtils.isEmpty(price)) {
                return;
            }
            float fprice = Float.valueOf(s.toString());
            float volum = Float.valueOf(sv);
            DecimalFormat df = new DecimalFormat("#.##");
            mPrice.setText(df.format(fprice * volum) + "");
            oilAddPriceStr = String.valueOf(fprice * volum);
        }
    };

    public static void gotoTrafficOilLogActivity(MyBasicActivity context, EventOilLogEntitiy oilLogEntitiy,
            String vid) {
        Intent intent = new Intent(context, TrafficOilLogActivity.class);
        intent.putExtra(OILLOG_ENTITY, oilLogEntitiy);
        intent.putExtra(OILLOG_VID, vid);
        context.startActivity(intent);
    }

    @Override
    protected void setTitle() {
        titleBar.setLeftImageResource(R.mipmap.nav_back);
        titleBar.setLeftText(" ");
        titleBar.setTitle(getResources().getString(R.string.oil_record));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_oil_log;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        oilType = new OilType(mContext);
        textVariety.setText("汽油");
        if (getIntent() != null && getIntent().hasExtra(OILLOG_ENTITY)) {
            this.oilLogEntitiy = (EventOilLogEntitiy) getIntent().getSerializableExtra(OILLOG_ENTITY);
            vid = getIntent().getStringExtra(OILLOG_VID);
            if (this.oilLogEntitiy != null) {
                bindView(this.oilLogEntitiy);
            }
        }
        mUserManger = new TruckManager(this);
        initData();
        editPrice.addTextChangedListener(twprice);
        editAmount.addTextChangedListener(tw);
        utils = new GetTimeUtils(time, this);
    }

    private void bindView(EventOilLogEntitiy oilLogEntitiy) {
        textVariety.setText(oilLogEntitiy.getOilType());
        editKiml.setText(oilLogEntitiy.getOilDistance());
        editAmount.setText(oilLogEntitiy.getOilCount());
        editPrice.setText(oilLogEntitiy.getOilPrice());
        mPrice.setText(oilLogEntitiy.getOilAddPrice());
        /*editPriceByKiml.setText(oilLogEntitiy.getOilMpg());*/
        mYear.setText(new SimpleDateFormat("yyyy-MM-dd").format(AppUtils.getDate(oilLogEntitiy.getOilDate())));
        mTime.setText(new SimpleDateFormat("HH:mm").format(AppUtils.getDate(oilLogEntitiy.getOilDate())));
        dateStr = oilLogEntitiy.getOilDate();
    }

    @OnClick({R.id.oil_log_variety_layout, R.id.oil_log_btn_sure, R.id.tv_time, R.id.tv_year})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.oil_log_variety_layout:
                if (oilType == null) {
                    oilType = new OilType(mContext);
                }
                oilType.showAsDropDown(oilVaritey);
                break;
            case R.id.oil_log_btn_sure:
                if (checkOk()) {
                    EventBusSendFactory.oilLogEvent(oilLogEntitiy);
                    finish();
                }
                break;
            case R.id.tv_time:
                if (dateStr != null) {
                    utils.getHourMintue(mTime, AppUtils.getDate(dateStr));
                } else {
                    utils.getHourMintue(mTime, null);
                }
                break;
            case R.id.tv_year:
                if (dateStr != null) {
                    utils.getYearMonthDay(mYear, "1", AppUtils.getDate(dateStr));
                } else {
                    utils.getYearMonthDay(mYear, "1", null);
                }
                break;
        }
    }

    private boolean checkOk() {
        String oilTypeStr = textVariety.getText().toString().trim() + "";
        String oilCardStr = editCardNum.getText().toString().trim() + "";
        if (utils.getDate() != null) {
            dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(utils.getDate());
        }
        String oilKimlStr = editKiml.getText().toString().trim() + "";
        oilAmountStr = editAmount.getText().toString().trim() + "";
        String oilPriceStr = editPrice.getText().toString().trim() + "";
        /*String oilPriceByKimlStr = editPriceByKiml.getText().toString().trim() + "";*/
        if (CommonUtils.isEmpty(oilTypeStr)) {
            T.showShort(mContext, "请选择油料品种");
            return false;
        }
     /*   if (CommonUtils.isEmpty(oilCardStr)) {
            T.showShort(mContext, "请输入油卡卡号");
            return false;
        }*/
        if (CommonUtils.isEmpty(dateStr) || "请选择日期".equals(mYear) || "请选择时间".equals(mTime)) {
            T.showShort(mContext, "请选择收车时间");
            return false;
        }
        oilLogEntitiy = new EventOilLogEntitiy(
                oilTypeStr,
                oilCardStr,
                dateStr,
                oilKimlStr,
                oilAmountStr,
                oilPriceStr,
                oilAddPriceStr
                /*oilPriceByKimlStr*/
        );
        return true;
    }

    private void initData() {
        if (mUserManger.checkNetwork(this)) {
            if (mDetailTask != null && mDetailTask.getStatus() == AsyncTask.Status.RUNNING) {
                mDetailTask.cancel(true);
            }
            mDetailTask = new DetailTask();
            mDetailTask.execute();
        } else {
            mUserManger.showToastMessage(getString(R.string.toast_no_network), 1000);
        }
    }

    private void setData(TruckDetailBean info) {
        editCardNum.setText(info.getOILCARD());
    }

    class OilType extends PopupWindow {
        public OilType(Context context) {
            super(context);
            View view = LayoutInflater.from(context).inflate(R.layout.popup_oil_type, null);
            ButterKnife.bind(this, view);
            setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setBackgroundDrawable(new BitmapDrawable());
            setContentView(view);
            setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams lp1 = getWindow().getAttributes();
                    lp1.alpha = 1.0f;
                    getWindow().setAttributes(lp1);
                }
            });
        }

        @OnClick({R.id.oil_type_gasoline, R.id.oil_type_rape})
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.oil_type_gasoline:
                    textVariety.setText("汽油");
                    dismiss();
                    break;
                case R.id.oil_type_rape:
                    textVariety.setText("柴油");
                    dismiss();
                    break;
            }
        }
    }

    /**
     * 开启请求数据线程
     */
    public class DetailTask extends AsyncTask<String, Void, TruckDetailEntity> {

        @Override
        protected TruckDetailEntity doInBackground(String... params) {
            showNormalDialog(DialogCreater.DIALOG_PROGRESS);
            String vd = vid;
            return mUserManger.detailTruckFromServer(vd);
        }

        @Override
        protected void onPostExecute(TruckDetailEntity s) {
            super.onPostExecute(s);
            dismissNormalDialog();
            if (s.getStatus().equals(Constant.RETURN_RESULT_OK)) {
                setData(s.getContent());
            } else if (s.getStatus().equals(Constant.JSON_DETE_ERROR)) {
                mUserManger.showToastMessage(getString(R.string.message_error), 1000);
            } else {
                mUserManger.showToastMessage(getString(R.string.toast_connect_server_failed), 1000);
            }
        }
    }
}
